package com.movies.service.config;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

import com.movies.service.service.AdminService;
import com.movies.service.service.UserService;
import com.movies.service.entity.Admin;
import com.movies.service.entity.User;


@Component
public class SaTokenRolePermissionImpl implements StpInterface {

    @Autowired
    private AdminService adminService;

    @Autowired
    private UserService userService;

//    权限列表
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return new ArrayList<>();
    }

//    角色列表
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<String> roles = new ArrayList<>();
        String resolved = null;
        Long id = null;
        try {
            if (loginId != null) {
                id = Long.valueOf(loginId.toString());
            }
        } catch (Exception ignored) {}
        if (id != null) {
            Admin admin = adminService.getById(id);
            if (admin != null) {
                String r = admin.getRole() != null ? admin.getRole().toString() : "ADMIN";
                resolved = r;
            } else {
                User user = userService.getById(id);
                if (user != null) {
                    String r = user.getRole() != null ? user.getRole().toString() : "USER";
                    resolved = r;
                }
            }
        }
        if (resolved == null) {
            // 默认角色回退
            resolved = "USER";
        }
        roles.add(resolved.toUpperCase());
        return roles;
    }
}